<?php
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
include_once dirname(__FILE__) . '/inc/phonecode/sendSms.php';
include_once dirname(__FILE__) . '/inc/common/AliyunVod.php';
include_once dirname(__FILE__) . '/inc/common/userinfo.php';
include_once dirname(__FILE__) . '/inc/common/wxapi.php';
include_once dirname(__FILE__) . '/inc/common/WxPayJsApiPay.php';
include_once dirname(__FILE__) . '/library/phpexcel/PHPExcel.php';
include_once dirname(__FILE__) . '/library/qrcode/phpqrcode.php';
require_once IA_ROOT . '/addons/goouc_class/inc/qiniu/autoload.php';
class goouc_class_plugin_h5ModuleSite extends WeModuleSite
{
    public $userid = 29;
    public $msg = '无此操作权限';

    public $t_cardinfo = 'goouc_class_cardinfo';
    public $t_banner = 'goouc_class_banner';
    public $t_lesson = 'goouc_class_lesson';
    public $t_son = 'goouc_class_son';
    public $t_city = 'goouc_class_city';
    public $t_teacher = 'goouc_class_teacher';
    public $t_subject = 'goouc_class_subject';
    public $t_class = 'goouc_class_class';
    public $t_classtype = 'goouc_class_classtype';
    public $t_semester = 'goouc_class_semester';
    public $t_voidtype = 'goouc_class_voidtype';
    public $t_level = 'goouc_class_level';
    public $t_shartitle = 'goouc_class_shartitle';
    public $t_poster = 'goouc_class_poster_new';
    public $t_user = 'goouc_class_user';
    public $t_signin = 'goouc_class_signin';
    public $t_signup = 'goouc_class_user_signup';
    public $t_phonecode = 'goouc_class_phonecode';
    public $t_userlooktime = 'goouc_class_userlook';
    public $t_userlooktimes = 'goouc_class_userlookm';
    public $t_user_exchange = 'goouc_class_user_exchange';
    public $t_user_group = 'goouc_class_user_group';
    public $t_user_group_info = 'goouc_class_user_group_info';
    public $t_order = 'goouc_class_order';
    public $t_user_study_speed = 'goouc_class_user_study_speed';
    public $t_live_message = 'goouc_class_live_message';
    public $t_user_study_now = 'goouc_class_user_study_sign';
    public $t_user_token = 'goouc_class_user_token';
    public $t_category = 'goouc_class_category';
    public $t_article = 'goouc_class_article';
    public $t_practice = 'goouc_class_practice';


    public function addlog($arr)
    {
        global $_W, $_GPC;
        $arr['ip'] = $_SERVER['REMOTE_ADDR'];
        $arr['addtime'] = time();
        return pdo_insert('goouc_class_syslog', $arr);
    }

    public function updateCache($fname, $content = NULL)
    {
        if (empty($content)) {
            $content = $this->getsetting();
        }

        cache_delete($fname);

        cache_write($fname, $content);
    }

    //开启curl get请求
    public function curl_get($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        return $data;
    }

    //开启curl post请求
    public function get_http_array($url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   //没有这个会自动输出，不用print_r();也会在后面多个1
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        return $output;
    }

    public function deleteimage($pid)
    {
        $this->deldir(MODULE_ROOT . '/images/Poster/poster/' . $pid . '/');
        $this->deldir(MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/');
        $this->deldir(MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/');
    }

    public function deldir($path)
    {
        //如果是目录则继续
        if (is_dir($path)) {
            //扫描一个文件夹内的所有文件夹和文件并返回数组
            $p = scandir($path);
            foreach ($p as $val) {
                //排除目录中的.和..
                if ($val != "." && $val != "..") {
                    //如果是目录则递归子目录，继续操作
                    if (is_dir($path . $val)) {
                        //子目录中操作删除文件夹和文件
                        deldir($path . $val . '/');
                        //目录清空后删除空文件夹
                        @rmdir($path . $val . '/');
                    } else {
                        //如果是文件直接删除
                        unlink($path . $val);
                    }
                }
            }
        }
    }

    /***********H5接口************/
    //跨域返回数据
    public function getresult($errno, $message, $data = '')
    {
//        $allow_origin = array(
//            '127.0.0.1',
//            '193.112.221.128',
//            '192.168.1.111'
//        );
//        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';  //跨域访问的时候才会存在此字段
//        if (in_array($origin, $allow_origin)) {
//            header('Access-Control-Allow-Origin:' . $origin);
//            header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
//            header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
//            exit(json_encode(array(
//                'errno' => $errno,
//                'message' => $message,
//                'data' => $data,
//            )));
//        }

        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS,PATCH');
        exit(json_encode(array(
            'errno' => $errno,
            'message' => $message,
            'data' => $data,
        )));

    }

    //验证是不是手机号
    public function is_Mobile($Argv)
    {
        $RegExp = "/^[1][3,4,5,6,7,8,9][0-9]{9}$/";
        return preg_match($RegExp, $Argv) ? $Argv : false;
    }

    /**
     * 七牛云图片
     */
    public function getImgUrl($img)
    {
        global $_W;
        //获取七牛配置
        $setting = pdo_get('uni_settings', array('uniacid' => $_W['uniacid']), array('remote'));
        $config = unserialize($setting['remote']);
        $qiniuConfig = $config['qiniu'];
        if ($config['type'] == 3) {
            $url = $qiniuConfig['url'];
            $imgurl = $url . '/' . $img;
        } else {
            $imgurl = $_W['siteroot'] . 'attachment/' . $img;
        }
        return $imgurl;
    }

    /**
     * 生成token
     */
    public function createtoken()
    {
        $str = md5(uniqid(md5(microtime(true)), true));  //生成一个不会重复的字符串
        $str = sha1($str);  //加密
        return $str;
    }

    /**
     * 验证token
     */
    public function checktoken($uid, $token)
    {
        global $_W, $_GPC;
        $createtime = pdo_get($this->t_user_token, array('uid' => $uid, 'token' => $token, 'weid' => $_W['uniacid']));
        if (empty($createtime['createtime'])) {
            return 1003;//token 不存在  非法访问
        }
        //通过考试时间来设定token过期时间
        $endtime = $createtime['createtime'] + 7200;
        if ($endtime > time()) {
            return 1001;//token正确
        } else {
            return 1002;//token超时  重新获取
        }
    }


    /************配合成成海报的函数**************/
    public function mkqrcode($uid)
    {
        $account_api = WeAccount::create();
        //还要做一个针对这个海报的头像大小
        $response = $account_api->getCodeLimit('pages/selected/selected?u=' . $uid, 430, array(
            'auto_color' => false,
            'line_color' => array(
                'r' => '#ABABAB',
                'g' => '#ABABAC',
                'b' => '#ABABAD',
            ),
            'is_hyaline' => false
        ));
        if (is_error($response)) {
            $message = ['code' => $response['errno'], 'msg' => $response['message']];
        } else {
            $message = ['code' => 200, 'content' => $response['content']];
        }
        return json_encode($message);
    }

    public function mkqrcodes($uid = 0, $new_file = '', $weid = 0)
    {
        $url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . "/addons/goouc_class/vue/index.html?i=" . $weid . "#/home?uid=" . $uid;
        /*生成二维码*/
        $data = $url;
        $level = 'L';// 纠错级别：L、M、Q、H
        $size = 4;// 点的大小：1到10,用于手机端4就可以了
        $QRcode = new \QRcode();
        $new_file = $new_file . 'qrcode_' . $uid . '.jpg';
        return $QRcode->png($data, $new_file, $level, $size);
    }

    public function mkqrcode1($uid, $lessonid, $sonid)
    {
        global $_W, $_GPC;
        $appid = $_W['account']['key'];
        $secret = $_W['account']['secret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
        $access_token = json_decode($this->curl_get($url), true)['access_token'];
        // header('content-type:image/jpg');//格式自选，不同格式貌似加载速度略有不同，想加载更快可选择jpg
        $data = array();
        $data['page'] = 'pages/selected/selected';//路径
        // $data['path'] = '';//路径
        // $data['scene'] = 'uid='.$uid.'&lid='.$lessonid.'&page=SD';//场景参数
        $data['scene'] = 'u=' . $uid . '&l=' . $lessonid . '&p=SD&s=' . $sonid;
        $data = json_encode($data);
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
        $da = $this->get_http_array($url, $data);
        return json_encode($da);
    }

//制作二维码对应海报的图片
    public function editqrcode($uid, $pid)
    {

        $info = pdo_get($this->t_poster, ['id' => $pid]);
        //var_dump($info);var_dump($uid);var_dump($pid);die;
        $info['qrcode_width_px'] = $info['qrcode_width_px'] / 0.7;
        $info['qrcode_height_px'] = $info['qrcode_height_px'] / 0.7;
        $res = $this->tailoring(MODULE_ROOT . '/images/Poster/qrcode/qrcode/qrcode_' . $uid . '.jpg', MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/' . $uid . '.png', $info['qrcode_width_px'], $info['qrcode_height_px']);
        if (is_error($res)) {
            $message = ['code' => 404, 'msg' => '图片生成失败'];
        } else {
            $message = ['code' => 200, 'msg' => '图片生成成功'];
        }
        return json_encode($message);
        exit;
    }

    public
    function editqrcodes($uid, $pid)
    {
        $info = pdo_get($this->t_poster, ['id' => $pid]);
        $info['qrcode_width_px'] = $info['qrcode_width_px'] / 0.7;
        $info['qrcode_height_px'] = $info['qrcode_height_px'] / 0.7;
        $res = $this->tailoring(MODULE_ROOT . '/images/Poster/qrcode/qrcode/qrcode_' . $uid . '.jpg', MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/' . $uid . '.png', $info['qrcode_width_px'], $info['qrcode_height_px']);
        if (is_error($res)) {
            $message = ['code' => 404, 'msg' => '图片生成失败'];
        } else {
            $message = ['code' => 200, 'msg' => '图片生成成功'];
        }
        return json_encode($message);
        exit;
    }

    public
    function hteditqrcodes($uid, $pid, $file)
    {
        $info = pdo_get($this->t_poster, ['id' => $pid]);
        $info['qrcode_width_px'] = $info['qrcode_width_px'] / 0.7;
        $info['qrcode_height_px'] = $info['qrcode_height_px'] / 0.7;
        $res = $this->tailoring($file, MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/' . $uid . '.png', $info['qrcode_width_px'], $info['qrcode_height_px']);
        if (is_error($res)) {
            $message = ['code' => 404, 'msg' => '图片生成失败'];
        } else {
            $message = ['code' => 200, 'msg' => '图片生成成功'];
        }
        return json_encode($message);
        exit;
    }

    public
    function editqrcode1($uid, $pid, $lessonid)
    {
        $info = pdo_get($this->t_poster, ['id' => $pid]);
        $info['qrcode_width_px'] = $info['qrcode_width_px'] / 0.7;
        $info['qrcode_height_px'] = $info['qrcode_height_px'] / 0.7;
        $res = $this->tailoring(MODULE_ROOT . '/images/Poster/lesson/qrcode/' . $uid . '_' . $lessonid . '.jpg', MODULE_ROOT . '/images/Poster/lesson/qrcodeposter/' . $pid . '/' . $uid . '_' . $lessonid . '.png', $info['qrcode_width_px'], $info['qrcode_height_px']);
        if ($res) {
            $message = ['code' => 200, 'msg' => '图片生成成功'];
        } else {
            $message = ['code' => 404, 'msg' => '图片生成失败'];
        }
        return json_encode($message);
    }

//下载用户头像到服务器
    public
    function getSecond($url, $new_file)
    {
        $header = array(
            'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
            'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
            'Accept-Encoding: gzip, deflate',);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $data = curl_exec($curl);
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        if ($code == 200) {//把URL格式的图片转成base64_encode格式的！
            $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
            $img_content = $imgBase64Code;//图片内容
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)) {
                $type = $result[2];//得到图片类型png?jpg?gif?
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))) {
                    return true;
                } else {
                    return false;
                }
            }
        }

    }

//制作用户头像对应海报的图片
    public function editheadimg($uid, $pid)
    {
        $info = pdo_get($this->t_poster, ['id' => $pid]);
        $info['head_width_px'] = $info['head_width_px'] / 0.7;
        $info['head_height_px'] = $info['head_height_px'] / 0.7;
        $res = $this->tailoring(MODULE_ROOT . '/images/Poster/headerimg/header/' . $uid . '.png', MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/' . $uid . '.png', $info['head_width_px'], $info['head_height_px']);
        if (is_error($res)) {
            $message = ['code' => 404, 'msg' => '图片生成失败'];
        } else {
            $message = ['code' => 200, 'msg' => '图片生成成功'];
        }
        return json_encode($message);
        exit;
    }

//制作用户头像对应海报的图片
    public function hteditheadimg($uid, $pid, $file)
    {
        $info = pdo_get($this->t_poster, ['id' => $pid]);
        $info['head_width_px'] = $info['head_width_px'] / 0.7;
        $info['head_height_px'] = $info['head_height_px'] / 0.7;
        $res = $this->tailoring($file, MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/' . $uid . '.png', $info['head_width_px'], $info['head_height_px']);
        if (is_error($res)) {
            $message = ['code' => 404, 'msg' => '图片生成失败'];
        } else {
            $message = ['code' => 200, 'msg' => '图片生成成功'];
        }
        return json_encode($message);
        exit;
    }

//修改图片大小
    public
    function tailoring($img_path, $new_img_path, $width, $height)
    {
        $img_info = @getimagesize($img_path);
        if (!$img_info || $width < 1 || $height < 1 || empty($new_img_path)) {
            return false;
        }
        if (strpos($img_info['mime'], 'jpeg') !== false) {
            $pic_obj = imagecreatefromjpeg($img_path);
        } else if (strpos($img_info['mime'], 'gif') !== false) {
            $pic_obj = imagecreatefromgif($img_path);
        } else if (strpos($img_info['mime'], 'png') !== false) {
            $pic_obj = imagecreatefrompng($img_path);
        } else {
            return false;
        }
        $pic_width = imagesx($pic_obj);
        $pic_height = imagesy($pic_obj);
        if (function_exists("imagecopyresampled")) {
            $new_img = imagecreatetruecolor($width, $height);
            imagecopyresampled($new_img, $pic_obj, 0, 0, 0, 0, $width, $height, $pic_width, $pic_height);
        } else {
            $new_img = imagecreate($width, $height);
            imagecopyresized($new_img, $pic_obj, 0, 0, 0, 0, $width, $height, $pic_width, $pic_height);
        }
        if (preg_match('~.([^.]+)$~', $new_img_path, $match)) {
            $new_type = strtolower($match[1]);
            switch ($new_type) {
                case 'jpg':
                    imagejpeg($new_img, $new_img_path);
                    break;
                case 'gif':
                    imagegif($new_img, $new_img_path);
                    break;
                case 'png':
                    imagepng($new_img, $new_img_path);
                    break;
                default:
                    imagejpeg($new_img, $new_img_path);
            }
        } else {
            imagejpeg($new_img, $new_img_path);
        }
        imagedestroy($pic_obj);
        imagedestroy($new_img);
        return true;
    }

//16进制颜色转rgb
    public
    function hex2rgb($hexColor)
    {
        $color = str_replace('#', '', $hexColor);
        if (strlen($color) > 3) {
            $rgb = array(
                'r' => hexdec(substr($color, 0, 2)),
                'g' => hexdec(substr($color, 2, 2)),
                'b' => hexdec(substr($color, 4, 2))
            );
        } else {
            $color = $hexColor;
            $r = substr($color, 0, 1) . substr($color, 0, 1);
            $g = substr($color, 1, 1) . substr($color, 1, 1);
            $b = substr($color, 2, 1) . substr($color, 2, 1);
            $rgb = array(
                'r' => hexdec($r),
                'g' => hexdec($g),
                'b' => hexdec($b)
            );
        }
        return $rgb;
    }

    /************配合成成海报的函数**************/
    /***3.0辅助函数开始****/
//获取opdnid
    public
    function getopenidnew($code)
    {
        global $_W, $_GPC;
        $appid = $_W['account']['key'];
        $secret = $_W['account']['secret'];
        $api = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
        $str = $this->httpGet($api);
        return $str;
    }

//购买函数
    public function userpay($uid, $lessonid, $type = 1, $groupid = 0, $usercardid = 0)
    {
        /*
         *type = 1 原价购买 2 开团支付 3 参团支付 4 使用兑课券支付
         *  */
        global $_W;
        $userinfo = pdo_get($this->t_user, array('id' => $uid));
        $lessoninfo = pdo_get($this->t_lesson, array('id' => $lessonid));
        $config = $this->getConfig($_W['uniacid']);
        //判断有没有购买过这个课程的订单
        $is_pay = pdo_get($this->t_order, array('userid' => $userinfo['id'], 'dataid' => $lessoninfo['id'], 'weid' => $_W['uniacid'], 'type' => 1));
        $payset = array('appid' => $config['h5_appid'], 'appsecret' => $config['h5_appsecret'], 'mchid' => $config['mchid'], 'shkey' => $config['pay_secret']);

        if (empty($lessoninfo) || $lessoninfo['status'] == 0) {
            $message = ['code' => 3003, 'msg' => '要购买的课程或章节不存在'];
            return $message;
        }
        $order = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $uid . $lessonid;


        if ($type == 2 || $type == 3) {
            $money = (int)(floatval($lessoninfo['old_money']) * 100);
            $data['true_money'] = $lessoninfo['old_money'];
            $data['groupid'] = $groupid;
        } elseif ($type == 4) {
            //查出兑课券抵扣金额
            $cardinfo = pdo_fetch("select * from " . tablename($this->t_user_exchange) . " ue JOIN " . tablename($this->t_cardinfo) . " c ON ue.cid = c.id where ue.id = :id ", array(':id' => $usercardid));
            $money = (int)(floatval($lessoninfo['pay_money']) * 100) - (int)(floatval($cardinfo['price']) * 100);
            $data['true_money'] = $lessoninfo['pay_money'] - $cardinfo['price'];
            $data['usercardid'] = $usercardid;
        } else {
            $money = (int)(floatval($lessoninfo['pay_money']) * 100);
            $data['true_money'] = $lessoninfo['pay_money'];
        }
        $data['weid'] = $_W['uniacid'];
        $data['dataid'] = $lessonid;
        $data['type'] = $type;
        $data['openid'] = $userinfo['h5_openid'];
        $data['userid'] = $uid;
        $data['out_trade_no'] = $order;
        $data['all_money'] = $lessoninfo['pay_money'];
        $data['order_status'] = 0;
        $data['createtime'] = time();
        $data['module'] = 2;

        $res = pdo_insert($this->t_order, $data);
        $payment_id = pdo_insertid();
        if (!$res) {
            $message = ['code' => 1001, 'msg' => '生成订单失败'];
            return $message;
        }
        $nonce_str = getNonceStr(32);
        $spbill_create_ip = $_SERVER['REMOTE_ADDR'];
        $notify_url = $_W['siteroot'] . "addons/goouc_class/wxresult.php";
        $dataurl = array(
            'appid' => $config['h5_appid'],
            'mch_id' => $payset['mchid'],
            'nonce_str' => $nonce_str,
            'body' => $lessoninfo['title'],
            'out_trade_no' => $order,
            'total_fee' => $money,
            'spbill_create_ip' => $spbill_create_ip,
            'notify_url' => $notify_url,
            'trade_type' => 'JSAPI',
            'openid' => $userinfo['h5_openid']
        );
       // var_dump($dataurl);die;
        $sign = getSign($dataurl, $payset['shkey']);
        $dataurl['sign'] = $sign;
        $xml = arrayToXml($dataurl);
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $res = xmlToUrl($xml, $url);
        libxml_disable_entity_loader(true);
        $xmlstr = simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);
        $returnarr = json_decode(json_encode($xmlstr), true);
        $message = [];
        if ($returnarr['return_code'] == "SUCCESS" && $returnarr['result_code'] == "SUCCESS") {
            $prepay_id = $returnarr['prepay_id'];
            $data = [];
            $data = array(
                'appId' => $config['h5_appid'],
                'timeStamp' => '"' . time() . '"',
                'nonceStr' => $nonce_str,
                'package' => "prepay_id=" . $prepay_id,
                'signType' => 'MD5',
            );
            $paysign = getSign($data, $payset['shkey']);
            $data['paySign'] = $paysign;
            $message['code'] = 200;
            $message['info'] = $data;
        } else {
            $message = ['code' => 1002, 'msg' => '请求支付失败', 'why' => $returnarr];
        }
        return $message;
    }

//get方式获取url信息
    public
    function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

//海报预览
    public
    function getposter($id = 2)
    {
        global $_W, $_GPC;
        $info = pdo_get($this->t_poster, array('weid' => $_W['uniacid'], 'id' => $id));
        if (empty($info)) {
            $message = ['code' => 3003, 'msg' => '没有海报背景图'];
            return $message;
        }
        $info['option'] = unserialize($info['option']);
        /*创建相应的文件夹*/
        $pid = $info['id'];
        $qrcodeposter_path = MODULE_ROOT . '/images/Poster/qrcode/';
        if (!is_dir($qrcodeposter_path)) {
            mkdir($qrcodeposter_path, 0777, true);
        }
        $qrcode_path = MODULE_ROOT . '/images/Poster/qrcode/qrcode';
        if (!is_dir($qrcode_path)) {
            mkdir($qrcode_path, 0777, true);
        }
        $headerimg_natival = MODULE_ROOT . '/images/Poster/headerimg/header/';
        if (!is_dir($headerimg_natival)) {
            mkdir($headerimg_natival, 0777, true);
        }
        $has_header_path = MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/';
        if (!is_dir($has_header_path)) {
            mkdir($has_header_path, 0777, true);
        }
        $has_header_path = MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/';
        if (!is_dir($has_header_path)) {
            mkdir($has_header_path, 0777, true);
        }
        $has_poster_path = MODULE_ROOT . '/images/Poster/poster/' . $pid . '/';
        if (!is_dir($has_poster_path)) {
            mkdir($has_poster_path, 0777, true);
        }
        $time = 999;
        $uid = $_W['uid'];
        //生成海报
        $y_image = imagecreatetruecolor(616, 846);
        $bgimg_path = $_W['attachurl'] . $info['bgimg'];
        $b_image = imagecreatefrompng($bgimg_path);
        imagecopymerge($y_image, $b_image, 0, 0, 0, 0, imagesx($b_image), imagesy($b_image), 100);
        $font = MODULE_ROOT . '/images/simhei.ttf';
        foreach ($info['option'] as $k => $v) {
            switch ($v) {
                //开启二维码
                case 1:
                    $file = $_W['siteroot'] . 'addons/goouc_class/images/img/qrcode.png'; //二维码
                    //去制作对应还包的二维码图片
                    $res = json_decode($this->hteditqrcodes($uid, $pid, $file), true);
                    if ($res['code'] != 200) {
                        $message = ['code' => 1002, 'msg' => '合并二维码失败'];
                        return $this->result(1, '合并二维码失败', $message);
                        die();
                    }
                    //制作成功 合并二维码与画布
                    $qrcode_path = MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/' . $uid . '.png';
                    $q_image = imagecreatefrompng($qrcode_path);
                    imagecopymerge($y_image, $q_image, ($info['qrcode_left_px'] / 0.7), ($info['qrcode_top_px'] / 0.7), 0, 0, imagesx($q_image), imagesy($q_image), 100);
                //开启用户头像
                case 2:
                    //判断用户头像是否存在  以及用户头像对应这个海报的存在不存在
                    $headerimgFile = $_W['siteroot'] . 'addons/goouc_class/images/img/headimg.png'; //二维码
                    //去做这个头像
                    $res = json_decode($this->hteditheadimg($uid, $pid, $headerimgFile), true);
                    if ($res['code'] != 200) {
                        $message = ['code' => 1003, 'msg' => '修改用户头像大小失败'];
                        return $this->result(1, '修改用户头像大小失败');
                        die();
                    }
                    $headmg_path = MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/' . $uid . '.png';
                    $h_image = imagecreatefrompng($headmg_path);
                    imagecopymerge($y_image, $h_image, ($info['head_left_px'] / 0.7), ($info['head_top_px'] / 0.7), 0, 0, imagesx($h_image), imagesy($h_image), 100);
                    //合并头像到海报
                    break;
                //开启用户昵称
                case 3:
                    $nick_color = $this->hex2rgb($info['nick_font_color']);
                    $black = imagecolorallocate($y_image, $nick_color['r'], $nick_color['g'], $nick_color['b']);//字体颜色 RGB
                    $fontSize = ($info['nick_size_px'] / 0.7);   //字体大小
                    $circleSize = 0; //旋转角度
                    $left = ($info['nick_left_px'] / 0.7);      //左边距
                    $top = ($info['nick_top_px'] + $info['nick_size_px']) / 0.7;       //顶边距
                    imagefttext($y_image, $fontSize, $circleSize, $left, $top, $black, $font, '用户昵称');
                    break;
                //开启学习天数
                case 4:
                    $nick_color = $this->hex2rgb($info['study_day_font_color']);
                    $black = imagecolorallocate($y_image, $nick_color['r'], $nick_color['g'], $nick_color['b']);//字体颜色 RGB
                    $fontSize = ($info['study_day_size_px'] / 0.7);   //字体大小
                    $circleSize = 0; //旋转角度
                    $left = ($info['study_day_left_px'] / 0.7);      //左边距
                    $top = ($info['study_day_top_px'] + $info['study_day_size_px']) / 0.7;       //顶边距
                    imagefttext($y_image, $fontSize, $circleSize, $left, $top, $black, $font, '999');
                    break;
                //开启日期
                case 5:
                    $weekarray = array("日", "一", "二", "三", "四", "五", "六");
                    $week = "星期" . $weekarray[date("w", time())];
                    $date = date('Y/m/d', time()) . $week;
                    $nick_color = $this->hex2rgb($info['date_font_color']);
                    $black = imagecolorallocate($y_image, $nick_color['r'], $nick_color['g'], $nick_color['b']);//字体颜色 RGB
                    $fontSize = ($info['date_size_px'] / 0.7);   //字体大小
                    $circleSize = 0; //旋转角度
                    $left = ($info['date_left_px'] / 0.7);      //左边距
                    $top = ($info['date_top_px'] + $info['date_size_px']) / 0.7;       //顶边距
                    imagefttext($y_image, $fontSize, $circleSize, $left, $top, $black, $font, $date);
                    break;
            }
        }
        $res = imagepng($y_image, MODULE_ROOT . '/images/Poster/poster/' . $pid . '/' . $uid . '_' . $pid . '.png');
        $path = 'images/Poster/poster/' . $pid . '/' . $uid . '_' . $pid . '.png';
        if ($res) {
            return $path;
        } else {
            return false;
        }
    }

    /***3.0辅助函数结束****/

    /***********H5接口************/

    /*****************阿里云提交每题作业************************/


    /********************七牛一键上传*********************/
    public
    function file_dir_remote_uploads($dir_path, $config = [], $limit = 50)
    {
        global $_W;
        if (empty($_W['setting']['remote']['type'])) {
            return error(1, '未开启远程附件');
        }
        $dir_path = safe_gpc_path($dir_path);
        if (!empty($dir_path)) {
            $local_attachment = file_tree_limit($dir_path, $limit);
        } else {
            $local_attachment = array();
        }
        if (is_array($local_attachment) && !empty($local_attachment)) {
            foreach ($local_attachment as $attachment) {
                $filename = str_replace(ATTACHMENT_ROOT, '', $attachment);
                list($image_dir, $file_account) = explode('/', $filename);
                if ($file_account == 'global' || !file_is_image($attachment)) {
                    continue;
                }
                if (is_numeric($file_account)) {
                    $uni_remote_setting = uni_setting_load('remote', $file_account);
                }
                if (is_dir(ATTACHMENT_ROOT . 'images/' . $file_account) && !empty($uni_remote_setting['remote']['type'])) {
                    $qiniuConfig = $config;
                } else {
                    $qiniuConfig = $_W['setting']['remote_complete_info'];
                }
                $result = $this->file_remote_uploads($filename, $qiniuConfig);
                if (is_error($result)) {
                    return $result;
                }
            }
        }
        return true;
    }

    function file_remote_uploads($filename, $qiniuConfig, $auto_delete_local = true)
    {
        global $_W;
        load()->library('qiniu');
        $auth = new Qiniu\Auth($qiniuConfig['accesskey'], $qiniuConfig['secretkey']);
        $config = new Qiniu\Config();
        $uploadmgr = new Qiniu\Storage\UploadManager($config);
        $putpolicy = Qiniu\base64_urlSafeEncode(json_encode(array(
            'scope' => $qiniuConfig['bucket'] . ':' . $filename,
        )));
        $uploadtoken = $auth->uploadToken($qiniuConfig['bucket'], $filename, 3600, $putpolicy);
        list($ret, $err) = $uploadmgr->putFile($uploadtoken, $filename, ATTACHMENT_ROOT . '/' . $filename);

        if ($auto_delete_local) {
            file_delete($filename);
        }
        if ($err !== null) {
            return error(1, '远程附件上传失败，请检查配置并重新上传');
        } else {
            return true;
        }
    }
    public function uploadQiNiu($accessKey,$secretKey,$bucket,$imgpath){
        $uploadMgr = new UploadManager();
        $auth = new Auth($accessKey, $secretKey);
        // 生成上传Token
        $token = $auth->uploadToken($bucket);
        $filePath = IA_ROOT . '/attachment/' . $imgpath;
        list($ret, $err) = $uploadMgr->putFile($token, $imgpath, $filePath);
        return $err;
    }
    public function doWebGzsite() {
        global $_W, $_GPC;
        $setting = pdo_get('uni_account_modules',array('uniacid'=>$_W['uniacid'],'module'=>'goouc_class_plugin_h5'),array('settings'));
        $settings = unserialize($setting['settings']);
        if (checksubmit()) {
            $data['h5_appid'] = $_GPC['h5_appid'];
            $data['h5_appsecret'] = $_GPC['h5_appsecret'];
            $data['sharetitle'] = $_GPC['sharetitle'];
            $data['shareicon'] = $_GPC['shareicon'];
            if ($this->userid == $_W['uid']) {
                message($this->msg);
            }
            $res = $this->saveSettings($data);
            if ($res) {
                message('设置成功', '', 'success');
            } else {
                message('设置失败', '', 'error');
            }
        }
        include $this->template('web/gzsite');
    }
    public function getConfig($weid){
        $settings = pdo_get('uni_account_modules',array('uniacid'=>$weid,'module'=>'goouc_class'),array('settings'));
        $h5_settings= pdo_get('uni_account_modules',array('uniacid'=>$weid,'module'=>'goouc_class_plugin_h5'),array('settings'));
        $config = array_merge(unserialize($settings['settings']),unserialize($h5_settings['settings']));
        return $config;
    }
    //获取随机字符串
    function getRandomStr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}


?>